import { queryFaqList, deleteQuestion } from '../../services/faqManage';
import { isSuccess } from '../../utils/handleError';
import { message } from 'antd';

export default {
    namespace: 'faqManage',
    state: {
        faqList: [],
        selectedRowKeys: [],
        pagination: {
            current: 1,
            pageSize: 10,
            total: 0,
        }
    },
    subscriptions: {
        setup({ dispatch, history }) {
            history.listen((location) => {
                if (location.pathname.includes('faqManage')) {
                    dispatch({
                        type: 'query',
                        payload: {
                            size: 10,
                            start: 0,
                        }
                    });
                    dispatch({
                        type: 'updateState',
                        payload: {
                            selectedRowKeys: []
                        }
                    });
                }
            })
        },
    },
    effects: {
        * query({
            payload
        }, { put, call }) {
            const res = yield call(queryFaqList, payload);
            if (res.code === '200') {
                const { data } = res;
                yield put({
                    type: 'updateState',
                    payload: {
                        faqList: data.faqList,
                        pagination: {
                            current: payload.start / payload.size + 1,
                            pageSize: 10,
                            total: data.allCount,
                        }
                    }
                });
            }else{
                message.error(res.msg)
            }
        },
        * delete({
            payload
        }, { put, call }) {
            if (!payload.length) {
                message.info('请选择需要删除的数据！')
                return;
            }
            const hide = message.loading();
            const res = yield call(deleteQuestion, payload);
            setTimeout(hide, 0);
            if (res.code === '200') {
                message.success('删除成功！')
                yield put({
                    type: 'query',
                    payload: {
                        size: 10,
                        start: 0,
                    }
                });
                yield put({
                    type: 'updateState',
                    payload: {
                        selectedRowKeys: []
                    }
                });
            }else{
                message.error(res.msg)
            }
        },
    },
    reducers: {
        updateState(state, { payload }) {
            return {
                ...state,
                ...payload,
            }
        }
    },
}